package com.ning.cms.service.impl;

import com.ning.cms.TO.LoginTO;
import com.ning.cms.service.UserService;
import com.ning.common.util.JwtUtil;
import com.ning.common.util.PageUtil;
import com.ning.common.web.exception.CustomerException;
import com.ning.common.web.response.ResultCode;

import com.ning.user.bean.User;
import com.ning.user.dao.UserMapper;
import com.ning.user.dao.extend.UserExtendMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserExtendMapper userExtendMapper;

    @Override
    public String login(LoginTO loginTO) {
        User userFromDB = userExtendMapper.findByName(loginTO.getUsername());

        //用户账号是否存在
        if (userFromDB==null||!userFromDB.getPassword().equals(loginTO.getPassword())) {
            throw new CustomerException(ResultCode.USER_LOGIN_ERROR);
        }

        //账号是否被禁用
        if (userFromDB.getStatus()==1){
            throw new CustomerException(ResultCode.USER_ACCOUNT_FORBIDDEN);
        }

        Map<String,Object> info = new HashMap<>();
        info.put("username",userFromDB.getUsername());
        info.put("realname",userFromDB.getRealname());

        String token = JwtUtil.sign(String.valueOf(userFromDB.getUserId()), info);

        return token;
    }

    @Override
    public PageUtil findByPage(PageUtil pageUtil) {
        return null;
    }
}
